//
//  WYMomentPhotoView.m
//  FriendCircleDemo
//
//  Created by mac on 2018/9/27.
//  Copyright © 2018年 WY. All rights reserved.
//

#import "WYMomentPhotoView.h"

@implementation WYMomentPhotoView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        self.exclusiveTouch = YES;
    }
    return self;
}

-(void)setPicture:(WYPicture *)picture
{
    _picture = picture;
    /// 设置
    /// 移除动画
    [self.layer removeAnimationForKey:@"contents"];
    /// 请求图片
    @weakify(self);
    [self.layer setImageWithURL:picture.bmiddle.url
                       placeholder:WYPicturePlaceholder()
                           options:YYWebImageOptionAvoidSetImage
                        completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
                            @strongify(self);
                            
                            if (image && stage == YYWebImageStageFinished) {
                                NSInteger width = picture.bmiddle.width;
                                NSInteger height = picture.bmiddle.height;
                                CGFloat scale = (height / width) / (self.height / self.width);
                                if (scale < 0.99 || isnan(scale)) {
                                    // 宽图把左右两边裁掉
                                    self.contentMode = UIViewContentModeScaleAspectFill;
                                    self.layer.contentsRect = CGRectMake(0, 0, 1, 1);
                                } else {
                                    // 高图只保留顶部
                                    self.contentMode = UIViewContentModeScaleToFill;
                                    self.layer.contentsRect = CGRectMake(0, 0, 1, (float)width / height);
                                }
                                self.image = image;
                                if (from != YYWebImageFromMemoryCacheFast) {
                                    CATransition *transition = [CATransition animation];
                                    transition.duration = 0.15;
                                    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                                    transition.type = kCATransitionFade;
                                    [self.layer addAnimation:transition forKey:@"contents"];
                                }
                            }
                        }];
}

#pragma mark - Override
- (void)setHidden:(BOOL)hidden{
    /// 取消当前图片的请求
    if (hidden) [self.layer cancelCurrentImageRequest];
    
    [super setHidden:hidden];
}
@end
